package com.coupon.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coupon.admin.dto.CouponCreateDTO;
import com.coupon.admin.dto.CouponUpdateDTO;
import com.coupon.admin.dto.CouponQueryDTO;
import com.coupon.admin.entity.Coupon;
import com.coupon.admin.service.CouponService;
import com.coupon.common.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 优惠券管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/coupon")
@RequiredArgsConstructor
@Validated
public class CouponController {
    
    private final CouponService couponService;
    
    /**
     * 创建优惠券
     */
    @PostMapping
    public Result<Long> createCoupon(@Valid @RequestBody CouponCreateDTO createDTO) {
        try {
            Long couponId = couponService.createCoupon(createDTO);
            return Result.success(couponId);
        } catch (Exception e) {
            log.error("创建优惠券失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新优惠券
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateCoupon(@PathVariable Long id, 
                                       @Valid @RequestBody CouponUpdateDTO updateDTO) {
        try {
            boolean result = couponService.updateCoupon(id, updateDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("更新优惠券失败，ID: {}", id, e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 发布优惠券
     */
    @PostMapping("/{id}/publish")
    public Result<Boolean> publishCoupon(@PathVariable Long id) {
        try {
            boolean result = couponService.publishCoupon(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("发布优惠券失败，ID: {}", id, e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 停用优惠券
     */
    @PostMapping("/{id}/stop")
    public Result<Boolean> stopCoupon(@PathVariable Long id) {
        try {
            boolean result = couponService.stopCoupon(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("停用优惠券失败，ID: {}", id, e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除优惠券
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCoupon(@PathVariable Long id) {
        try {
            boolean result = couponService.deleteCoupon(id);
            return Result.success(result);
        } catch (Exception e) {
            log.error("删除优惠券失败，ID: {}", id, e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 分页查询优惠券
     */
    @GetMapping("/page")
    public Result<IPage<Coupon>> getCouponPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            CouponQueryDTO queryDTO) {
        try {
            Page<Coupon> page = new Page<>(current, size);
            IPage<Coupon> result = couponService.getCouponPage(page, queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("分页查询优惠券失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取优惠券详情
     */
    @GetMapping("/{id}")
    public Result<Coupon> getCouponDetail(@PathVariable Long id) {
        try {
            Coupon coupon = couponService.getCouponDetail(id);
            return Result.success(coupon);
        } catch (Exception e) {
            log.error("获取优惠券详情失败，ID: {}", id, e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 批量操作优惠券
     */
    @PostMapping("/batch")
    public Result<Boolean> batchOperateCoupons(@RequestBody BatchOperateRequest request) {
        try {
            boolean result = couponService.batchOperateCoupons(request.getIds(), request.getOperation());
            return Result.success(result);
        } catch (Exception e) {
            log.error("批量操作优惠券失败", e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取券效分析数据
     */
    @GetMapping("/{id}/analysis")
    public Result<Object> getCouponEffectAnalysis(@PathVariable Long id) {
        try {
            Object analysis = couponService.getCouponEffectAnalysis(id);
            return Result.success(analysis);
        } catch (Exception e) {
            log.error("获取券效分析失败，ID: {}", id, e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 检查券是否可以编辑
     */
    @GetMapping("/{id}/can-edit")
    public Result<Boolean> canEditCoupon(@PathVariable Long id) {
        try {
            boolean canEdit = couponService.canEditCoupon(id);
            return Result.success(canEdit);
        } catch (Exception e) {
            log.error("检查券编辑权限失败，ID: {}", id, e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新AI推荐权重
     */
    @PutMapping("/{id}/ai-weight")
    public Result<Boolean> updateAiWeight(@PathVariable Long id, 
                                        @RequestParam Double weight) {
        try {
            boolean result = couponService.updateAiWeight(id, weight);
            return Result.success(result);
        } catch (Exception e) {
            log.error("更新AI推荐权重失败，ID: {}", id, e);
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 批量操作请求DTO
     */
    public static class BatchOperateRequest {
        private List<Long> ids;
        private String operation;
        
        public List<Long> getIds() {
            return ids;
        }
        
        public void setIds(List<Long> ids) {
            this.ids = ids;
        }
        
        public String getOperation() {
            return operation;
        }
        
        public void setOperation(String operation) {
            this.operation = operation;
        }
    }
}
